package gosnoopers.fr;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import lazy_listview.JSONfunctions;
import lazy_listview.LazyAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import common.Common;
 
 
public class HomePage extends Activity {
	
    /** Called when the activity is first created. */

	public static int page = 1;
	public static int countItem = 0;
	public static boolean params = false;
	public static String language = "";
	// All static variables
	static String URL1 = "http://gosnoopers.com/victimes/app/getVictimes";
	static String URL = "http://gosnoopers.com/victimes/app/getVictimes";
	
	
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String FLAG = "flag";
    public static JSONObject jsonobject;
    public static JSONArray jsonarray;
    public static boolean stuckLoadMore = false;
    // ProgressBar
 	private View mProgressBarLoadMoreLayout;
 	private ProgressBar mProBarLoading;
 	private ProgressBar mProgressBarLoadMore;
    public int width=0;
 	
 	
	ListView list;
	LazyAdapter adapter;
	
	
    public  boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    final Context context = this;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		  
	      super.onCreate(savedInstanceState);
	      
	      if(language == ""){
	    	  	language = new SessionManager(getApplicationContext()).getLanguage();
	    	  	Locale locale = new Locale(language);
				Locale.setDefault(locale);
				Configuration config = new Configuration();
				config.locale = locale;
				getApplicationContext().getResources().updateConfiguration(config, null);
	      }
	      
	      this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	      setContentView(R.layout.homepage);
	      
	      
	      init();
	    //**************get size of device********************
	      DisplayMetrics metrics = context.getResources().getDisplayMetrics();
          width = metrics.widthPixels;
          //***************************************************
          params = false;
/*          Toast t = Toast.makeText(getApplicationContext(), LandingActivity.cities, Toast.LENGTH_SHORT);
    	  t.show();*/
    	  if(LandingActivity.cities != ""){
    		  URL = URL1+"?province_id="+LandingActivity.cities;
    		  params = true;
    	  }
    	  String MainURL = "";
    	  if(params){
    		  MainURL = URL+"&page=1";
    	  
    	  }else{
    		  MainURL = URL+"?page=1";
    	  }
          Log.d("URLHOMEPAGE:", URL.toString());
	      
	      if(!isNetworkAvailable()){
	    	  CharSequence text = Common.MSG;
	    	  Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
	    	  toast.show();
	      }else{
	    	  new DownloadJSON().execute();
	      }
	      
	}
	
	public void init() {
		// Locate the listview in listview_main.xml
    	list = (ListView) findViewById(R.id.list);
		// ProgressBar
		mProgressBarLoadMoreLayout =  ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
		mProBarLoading = (ProgressBar)findViewById(R.id.probar_loading);
		mProgressBarLoadMore = (ProgressBar)mProgressBarLoadMoreLayout.findViewById(R.id.progress_bar_load_more);
		mProgressBarLoadMore.setVisibility(View.GONE);
		list.addFooterView(mProgressBarLoadMoreLayout);
		
		
		HomePage.this.header();
		
		
	}
	public void  header(){
		ImageView btn_setting = (ImageView) findViewById(R.id.image_setting);
		btn_setting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(), Settings.class);
	            startActivity(goToNextActivity);
			}
		});
		
		/**
		 * Kiem user da dang nhap hay chua
		 * 1. hein thi icon user
		 * 2. hien thi icon add victimes
		 */
		ImageView image_open_left_navigation = (ImageView) findViewById(R.id.image_open_left_navigation);
		ImageView icon_header_form = (ImageView) findViewById(R.id.icon_header_form);
		if(MainActivity.userId.equalsIgnoreCase("0")){
			image_open_left_navigation.setVisibility(View.VISIBLE);
			icon_header_form.setVisibility(View.GONE);
		}else{
			image_open_left_navigation.setVisibility(View.GONE);
			icon_header_form.setVisibility(View.VISIBLE);
		}
		
		image_open_left_navigation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(), MainActivity.class);
	            startActivity(goToNextActivity);
			}
		});
		
		icon_header_form.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(), FormFirst.class);
	            startActivity(goToNextActivity);
			}
		});
	}
	
	
	public static boolean strError  = false;
	// DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProBarLoading.setVisibility(View.VISIBLE);
            Toast.makeText(getApplicationContext(), "Loading...", Toast.LENGTH_SHORT).show();
        }
 
        @Override
        protected Void doInBackground(Void... p) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            String _url = URL;
            params = false;
            
        	  if(LandingActivity.cities != ""){
        		  _url = URL+"&w="+width;
        	  }else{
        		  
        		  _url = URL+"?w="+width;
        	  }
            
            Log.i("AAAAAAAAAAAAAAAAAAA",_url);
            jsonobject = JSONfunctions.getJSONfromURL(_url);
            
            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("data");
                strError = jsonobject.getBoolean("error");
                countItem = jsonobject.getInt("count");
                String message = jsonobject.getString("message");
                if(!strError){
                	for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("name", jsonobject.getString("name"));
                        map.put("inscrition", jsonobject.getString("inscrition"));
                        map.put("local_victim", jsonobject.getString("local_victim"));
                        map.put("image_larger", jsonobject.getString("image_larger"));
                        map.put("id", jsonobject.getString("id"));
                       
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }

                	
                }else{
                	Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
      	    	  	toast.show();
                }
                
                
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }
 
        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new LazyAdapter(HomePage.this, arraylist);
            // Set the adapter to the ListView
            list.setAdapter(adapter);
            // Close the progressdialog
            if(strError){
            	Button try_again = (Button) findViewById(R.id.try_again);
            	try_again.setVisibility(View.VISIBLE);
            }else{
            	Button try_again = (Button) findViewById(R.id.try_again);
            	try_again.setVisibility(View.GONE);
            }
            
            list.setOnItemClickListener(new OnItemClickListener() {



  				@Override
  				public void onItemClick(AdapterView<?> arg0, View view,
  						int position, long id) {
  					// TODO Auto-generated method stub
  	                  	                 
  	                  TextView victime_id = (TextView) view.findViewById(R.id.victime_id);
  	                
  	                    

  	                Intent goToNextActivity = new Intent(getApplicationContext(), Details.class);
					goToNextActivity.putExtra("VICTIME_ID", victime_id.getText());
	               startActivity(goToNextActivity);
  					
  				}

              });
            
            
            
         // Create an OnScrollListener
            list.setOnScrollListener(new OnScrollListener() {
 
                @Override
                public void onScrollStateChanged(AbsListView view,
                        int scrollState) { // TODO Auto-generated method stub
                    int threshold = 1;
                    int count = list.getCount();
                    
                    if (scrollState == SCROLL_STATE_IDLE) {
                    	if(count < HomePage.countItem){
	                        if (list.getLastVisiblePosition() >= count
	                                - threshold) {
	                        	
	
	        	              	
	        	              	Log.i("COUNTCOUNTCOUNTCOUNT","AAAAAAAA "+count);
	                            // Execute LoadMoreDataTask AsyncTask
	        	              	if(!stuckLoadMore){
	        	              		new LoadMoreDataTask().execute();
	        	              		
	        	              	}
	                            
	                        }
                    	}
                    }
                }
 
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                        int visibleItemCount, int totalItemCount) {
                    // TODO Auto-generated method stub
 
                }
 
            });
            
            mProBarLoading.setVisibility(View.GONE);
        }
        
        
    }
    
    
    
    private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            stuckLoadMore = true;
            mProgressBarLoadMore.setVisibility(View.VISIBLE);
            Toast.makeText(getApplicationContext(), "Loading...", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected Void doInBackground(Void... params) {
        	// Create an array
            //arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            String MainURL = "";
            page = page + 1;
          	if(HomePage.params){
          		MainURL = URL+"&page="+page+"&w="+width;
          	  
          	}else{
          		MainURL = URL+"?page="+page+"&w="+width;
          	}
          	Log.i("COUNTCOUNTCOUNTCOUNT",MainURL);
            jsonobject = JSONfunctions.getJSONfromURL(MainURL);
           
            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("data");
                boolean strError = jsonobject.getBoolean("error");
                String message = jsonobject.getString("message");
                if(!strError){
                	for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("name", jsonobject.getString("name"));
                        map.put("inscrition", jsonobject.getString("inscrition"));
                        map.put("local_victim", jsonobject.getString("local_victim"));
                        map.put("image_larger", jsonobject.getString("image_larger"));
                        map.put("id", jsonobject.getString("id"));
                       
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                	
                }else{
                	Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
      	    	  	toast.show();
                }
                
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Locate listview last item
            int position = list.getLastVisiblePosition();
            // Pass the results into ListViewAdapter.java
            adapter = new LazyAdapter(HomePage.this, arraylist);
            // Binds the Adapter to the ListView
            list.setAdapter(adapter);
            // Show the latest retrived results on the top
            list.setSelectionFromTop(position, 0);
            mProgressBarLoadMore.setVisibility(View.GONE);
            stuckLoadMore = false;
        }
    }
    
}